package games.gong.durid.service.impl;

import games.gong.durid.entity.Permission;
import games.gong.durid.entity.Role;
import games.gong.durid.entity.User;
import games.gong.durid.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName SecurityService
 * @Description 权限检查服务类
 * @Author games
 * @Date 2025/8/10 上午10:23
 * @Version 1.0
 */
@Service("ss")
public class SecurityService {
    
    private static final Logger logger = LoggerFactory.getLogger(SecurityService.class);
    
    @Autowired
    private UserService userService;
    
    /**
     * 检查当前用户是否具有指定权限
     * @param permissionName 权限名称
     * @return 是否具有权限
     */
    public boolean hasPermission(String permissionName) {
        try {
            // 获取当前认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                logger.debug("Authentication is null or not authenticated");
                return false;
            }
            
            // 获取当前用户名
            String username = authentication.getName();
            logger.debug("Checking permission '{}' for user '{}'", permissionName, username);
            
            // 获取用户信息
            User user = userService.getUserByUsername(username);
            if (user == null) {
                logger.debug("User '{}' not found", username);
                return false;
            }
            
            // 获取用户角色
            List<Role> roles = userService.getRolesByUserId(user.getId());
            if (roles == null || roles.isEmpty()) {
                logger.debug("User '{}' has no roles", username);
                return false;
            }
            
            logger.debug("User '{}' has roles: {}", username, roles.stream().map(Role::getName).toList());
            
            // 检查角色对应的权限
            for (Role role : roles) {
                List<Permission> permissions = userService.getPermissionsByRoleId(role.getId());
                if (permissions != null) {
                    logger.debug("Role '{}' has permissions: {}", role.getName(), permissions.stream().map(Permission::getName).toList());
                    for (Permission permission : permissions) {
                        if (permissionName.equals(permission.getName())) {
                            logger.debug("User '{}' has permission '{}'", username, permissionName);
                            return true;
                        }
                    }
                }
            }
            
            logger.debug("User '{}' does not have permission '{}'", username, permissionName);
            return false;
        } catch (Exception e) {
            logger.error("Error checking permission '{}'", permissionName, e);
            return false;
        }
    }
}